﻿using BroadGoalComponents;
using BroadGoalComponents.Dialogs;
using BroadGoalComponents.Navigation;
using Custom.Controls;
using Custom.Framework;
using Custom.Infrastructure.EventBus;
using Custom.Model.Dto;
using Custom.Model.Entity;
using Custom.Service.Repository;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace Custom.Main
{
    public partial class frmMain : PlatFormBase, IEventHandler<TEventEntity>
    {
        private SysRoleMenuReporitory roleMenuReporitory = new SysRoleMenuReporitory();
        // 遮罩窗体
        private CoverForm coverFrm = new CoverForm();

        public frmMain()
        {
            InitializeComponent();

            // 注册事件总线
            EventBus.Instance.Subscribe(this);

            //解决闪烁
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

            // 最大化时显示任务栏
            this.SetFormMax(this);

            // 设置拖拽
            DragWindow drag = new DragWindow();
            drag.BindEvent(this, this.pnlTop);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            // 获取角色对应的菜单
            List<SysMenuDto> menus = roleMenuReporitory.GetRoleMenus(1);

            if (menus != null)
            {
                List<SysMenuDto> rootMenus = menus.Where(w => w.Pid == 0).ToList();

                this.createMenus(menus, rootMenus, null);
            }
            //return;

            // 获取首页（注意：作为首页的菜单ID必须是1）
            SysMenuDto home = menus.FirstOrDefault(f => f.IsHomePage == 1);
            // 默认打开首页
            if (home != null)
            {
                this.setHomePage(home.FormName, home.AssemblyName, home.Text);
            }
            else
            {
                this.bgTabControl1.TabPages.Clear();
            }
        }

        /// <summary>
        /// 设置窗体最大化（不遮挡任务栏）显示全屏
        /// </summary>
        /// <param name="frm"></param>
        public virtual void SetFormMax(Form frm)
        {
            this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.WorkingArea.Width + 10, Screen.PrimaryScreen.WorkingArea.Height + 1);
        }

        /// <summary>
        /// 主窗体最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        /// <summary>
        /// 主窗体还原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMax_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Maximized;
                //this.Invalidate(); // 重绘下控件，否则会显示有问题
            }
            else if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
                int screenTop = (System.Windows.Forms.Screen.GetWorkingArea(this).Width - this.Width) / 2;
                int screenLeft = (System.Windows.Forms.Screen.GetWorkingArea(this).Height - this.Height) / 2;
                if (this.WindowState == FormWindowState.Normal)
                {
                    this.Location = new Point(screenTop, screenLeft);
                }
            }
        }

        /// <summary>
        /// 程序退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            //// 二次确认？？？
            //DialogResult dialogResult = QuestionDialog.Show(this, "是否确认退出？");
            //if (dialogResult == DialogResult.Yes)
            //{  
            //    this.Close();
            //    this.DialogResult = DialogResult.OK;
            //}
        }

        /// <summary>
        /// 实现事件总线方法
        /// </summary>
        /// <param name="evt"></param>
        public void HandleEvent(TEventEntity evt)
        {
            switch (evt.ActionName)
            {
                case "showCover":
                    this.coverFrm.StartPosition = FormStartPosition.Manual;
                    this.coverFrm.Left = this.Left;
                    this.coverFrm.Top = this.Top;
                    this.coverFrm.Width = this.Width;
                    this.coverFrm.Height = this.Height;
                    if (!this.coverFrm.Visible)
                        this.coverFrm.Show(this);
                    break;
                case "hideCover":
                    this.coverFrm.Hide();
                    this.BringToFront();
                    break;
                case "setTopMost":
                    this.TopMost = true;
                    break;
                case "cancelTopMost":
                    this.TopMost = false;
                    break;
            }
        }
        /// <summary>
        /// 点击打开菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.openMenu(e.ClickedItem.Name, e.ClickedItem.Tag?.ToString(), e.ClickedItem.Text);
        }

        /// <summary>
        /// 创建菜单
        /// </summary>
        /// <param name="sourceMenus"></param>
        /// <param name="menus"></param>
        /// <param name="parentItem"></param>
        private void createMenus(List<SysMenuDto> sourceMenus, List<SysMenuDto> menus, NavigationChildMenuItem parentItem = null)
        {
            if (sourceMenus.Count == 0 || menus.Count == 0) return;

            foreach (SysMenuDto menu in menus)
            {
                if (menu.Pid == 0)
                {
                    NavigationRootMenuItem item = new NavigationRootMenuItem()
                    {
                        Name = menu.FormName,
                        HoverBackColor = Color.FromArgb(71, 71, 72),
                        Text = "  " + menu.Text,
                        TextAlign = ContentAlignment.MiddleLeft,
                        Font = new Font("微软雅黑", 14, GraphicsUnit.Pixel)
                    };

                    List<SysMenuDto> childMenus = sourceMenus.Where(w => w.Pid == menu.Id).ToList();
                    if (childMenus.Count == 0)
                    {
                        item.IsExpanded = false;
                        item.Tag = menu.AssemblyName;
                    }
                    else
                    {
                        item.IsExpanded = true;
                    }

                    this.MenuStrip.Items.Add(item);
                    createMenus(sourceMenus, childMenus, item);
                }
                else
                {
                    NavigationChildMenuItem item = new NavigationChildMenuItem()
                    {
                        Name = menu.FormName,
                        HoverBackColor = Color.FromArgb(71, 71, 72),
                        ParentItem = parentItem,
                        Text = "  " + menu.Text,
                        TextAlign = ContentAlignment.MiddleLeft,
                        Font = new Font("微软雅黑", 14, GraphicsUnit.Pixel)
                    };

                    List<SysMenuDto> childMenus = sourceMenus.Where(w => w.Pid == menu.Id).ToList();
                    if (childMenus.Count == 0)
                    {
                        item.IsExpanded = false;
                        item.Tag = menu.AssemblyName;
                    }
                    else
                    {
                        item.IsExpanded = true;
                    }

                    this.MenuStrip.Items.Add(item);
                    createMenus(sourceMenus, childMenus, item);
                }
            }
        }

        /// <summary>
        /// 打开菜单
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="AssemblyName"></param>
        /// <param name="text"></param>
        private void openMenu(string strName, string AssemblyName, string text)
        {
            if (string.IsNullOrEmpty(strName) || string.IsNullOrEmpty(AssemblyName)) return;

            try
            {
                if (text.Trim() == "密码修改" || text.Trim() == "备份设置")
                {
                    string[] assemblylist = AssemblyName.Split('\\');
                    Assembly asm = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + AssemblyName + ".dll");
                    Type t = asm.GetType(strName, true);
                    DialogBase form = (DialogBase)Activator.CreateInstance(t);
                    form.Text = text;
                    form.ShowDialog(this);
                }
                else
                { 
                    TabPage page = this.findPage(strName);

                    if (page == null)
                    {
                        string[] assemblylist = AssemblyName.Split('\\');
                        Assembly asm = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + AssemblyName + ".dll");
                        Type t = asm.GetType(strName, true);
                        Form form = (Form)Activator.CreateInstance(t);
                        form.Text = text;
                        form.TopLevel = false;
                        form.FormBorderStyle = FormBorderStyle.None;

                        page = new TabPage()
                        {
                            Name = strName,
                            Text = text,
                            BackColor = Color.Transparent,
                            BorderStyle = BorderStyle.None,
                            AutoScroll = true
                        };

                        form.MdiParent = this;
                        page.Controls.Add(form);
                        this.bgTabControl1.TabPages.Add(page);
                        this.bgTabControl1.SelectedTab = page;
                        form.Dock = DockStyle.Fill; // 一定要放在controls.add()之后，否则不起作用
                        form.Show();
                    }
                    else
                    {
                        this.bgTabControl1.SelectedTab = page;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        /// 设置首页
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="AssemblyName"></param>
        /// <param name="text"></param>
        private void setHomePage(string strName, string AssemblyName, string text)
        {
            TabPage page = this.bgTabControl1.TabPages.Count > 0 ? this.bgTabControl1.TabPages[0] : null;

            if (page != null && page.Controls.Count == 0)
            {
                page.Text = text;
                page.Name = strName;
                string[] assemblylist = AssemblyName.Split('\\');
                Assembly asm = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + AssemblyName + ".dll");
                Type t = asm.GetType(strName, true);
                Form form = (Form)Activator.CreateInstance(t);
                form.Text = text;
                form.TopLevel = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Dock = DockStyle.Fill;
                page.Controls.Add(form);
                this.bgTabControl1.SelectedTab = page;
                form.Show();
            }
        }

        /// <summary>
        /// 根据Name查找已打开的标签页
        /// </summary>
        /// <param name="pageName"></param>
        /// <returns></returns>
        private TabPage findPage(string pageName)
        {
            if (this.bgTabControl1.TabPages.Count > 0)
            {
                foreach (TabPage page in this.bgTabControl1.TabPages)
                {
                    if (page.Name == pageName)
                        return page;
                }
            }

            return null;
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 设置成True，不会被关闭程序,给出提示框
            e.Cancel = true;
            DialogResult dialogResult = QuestionDialog.Show(this, "是否确认退出？");
            if (dialogResult == DialogResult.Yes)
            {
                Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"BackupTool.exe");
                //关闭程序             
                Process.GetCurrentProcess().Kill();
            }
        }
    }
}
